package app

import (
	"context"
	"fmt"
	"qrsj-collect/backend/hotkey"
	"qrsj-collect/backend/utils"
	"sync"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type HotkeyApp struct {
	ctx     context.Context
	mu      sync.Mutex
	hkSlice []string
}

func NewHotkeyApp() *HotkeyApp {
	return &HotkeyApp{}
}

func (a *HotkeyApp) Startup(ctx context.Context) {
	a.ctx = ctx
	a.hkSlice = make([]string, 0)
}

func (a *HotkeyApp) Shutdown(ctx context.Context) {
	a.UnregisterAllHotkeys()
}

func (a *HotkeyApp) RegisterHotkey(key string, eventName string, data interface{}) {
	a.mu.Lock()
	key = utils.ParseHotkey(key)
	for _, v := range a.hkSlice {
		if v == key {
			a.UnregisterHotkey(key)
		}
	}
	a.hkSlice = append(a.hkSlice, key)
	a.mu.Unlock()
	fmt.Println("注册快捷键", key, eventName, data)
	hotkey.Register(key, "down", func() {
		fmt.Println("触发快捷键", key, eventName, data)
		runtime.EventsEmit(a.ctx, eventName, data)
	})
}

func (a *HotkeyApp) UnregisterHotkey(key string) {
	a.mu.Lock()
	key = utils.ParseHotkey(key)
	hotkey.Unregister(key, "down")
	fmt.Println("清除当前快捷键", key)
	for i := 0; i < len(a.hkSlice); {
		if a.hkSlice[i] == key {
			a.hkSlice = append(a.hkSlice[:i], a.hkSlice[i+1:]...)
		} else {
			i++
		}
	}
	a.mu.Unlock()
}

func (a *HotkeyApp) UnregisterAllHotkeys() {
	for _, key := range a.hkSlice {
		key = utils.ParseHotkey(key)
		hotkey.Unregister(key, "down")
	}
	a.hkSlice = make([]string, 0)
	fmt.Println("清除所有快捷键")
}
